﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Threading.Tasks;
using Urs.Core;
using Urs.Data.Domain.Configuration;
using Urs.Data.Domain.Users;
using Plugin.Api.Infrastructure;
using Plugin.Api.Models.Account;
using Urs.Services.Localization;
using Urs.Services.Logging;
using Urs.Services.Users;
using Urs.Framework.Controllers;

/// <summary>
/// www.urselect.com 优社电商
/// </summary>
namespace Plugin.Api.Controllers
{
    /// <summary>
    /// 账号接口
    /// </summary>
    [ApiVersion("1.0")]
    [Route("api/v{version:apiVersion}/account")]
    [ApiController]
    public class AccountController : BaseApiController
    {
        private readonly ILocalizationService _localizationService;
        private readonly UserSettings _userSettings;
        private readonly IUserService _userService;
        private readonly IUserRegistrationService _userRegistrationService;
        private readonly IActivityLogService _activityLogService;
        private readonly OpenApiSettings _openApiSettings;
        /// <summary>
        /// 构造器
        /// </summary>
        public AccountController(ILocalizationService localizationService,
            UserSettings userSettings,
            IUserService userService,
            IUserRegistrationService userRegistrationService,
            IActivityLogService activityLogService,
            OpenApiSettings openApiSettings)
        {
            this._localizationService = localizationService;
            this._userSettings = userSettings;
            this._userService = userService;
            this._userRegistrationService = userRegistrationService;
            this._activityLogService = activityLogService;
            this._openApiSettings = openApiSettings;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="model">登录对象</param>
        /// <returns></returns>
        /// <response code="200">成功请求,用户授权数据</response>
        [HttpPost("login")]
        [ProducesResponseType(typeof(MoLoginInfo), 200)]
        public async Task<ApiResponse<MoLoginInfo>> Login(MoLogin model)
        {
            if (model == null)
                return ApiResponse<MoLoginInfo>.Warn("请求参数不能为空");

            if (ModelState.IsValid)
            {
                model.Name = model.Name.Trim();

                if (_userRegistrationService.Validate(model.Name, model.Password))
                {
                    var moLoginInfo = await Task.Run(() =>
                      {
                          var user = _userService.GetUsersByUsernameOrPhoneOrEmail(model.Name);
                          var claims = new Claim[]
                          {
                            new Claim(ClaimTypes.NameIdentifier,user.UserGuid.ToString()),
                          };

                          var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(_openApiSettings.JwtSecurityKey));
                          var expires = DateTime.Now.AddDays(_openApiSettings.Expires);
                          var token = new JwtSecurityToken(
                                      issuer: _openApiSettings.Issuer,
                                      audience: _openApiSettings.Audience,
                                      claims: claims,
                                      notBefore: DateTime.Now,
                                      expires: expires,
                                      signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256));

                          //生成accessToken
                          string jwtToken = new JwtSecurityTokenHandler().WriteToken(token);

                          _activityLogService.InsertActivity("PublicStore.Login", _localizationService.GetResource("ActivityLog.PublicStore.Login"), user);

                          return new MoLoginInfo() { Guid = user.UserGuid.ToString(), AccessToken = jwtToken, Nickname = user.GetFullName() };
                      });

                    return ApiResponse<MoLoginInfo>.Success(moLoginInfo);
                }
                else
                {
                    return ApiResponse<MoLoginInfo>.Warn(_localizationService.GetResource("Account.Login.WrongCredentials"));
                }
            }
            return ApiResponse<MoLoginInfo>.Warn(ModelState.FirstMessage());
        }

        /// <summary>
        /// 是否在线
        /// </summary>
        /// <returns>0/1  0为不在线，1为在线</returns>
        /// <response code="200">成功请求,登陆状态</response>
        [ApiAuthorize]
        [HttpGet("online")]
        [ProducesResponseType(typeof(int), 200)]
        public async Task<ApiResponse<int>> IsOnline()
        {
            if (!Guid.TryParse(RouteData.Values["guid"].ToString(), out Guid userGuid))
                return ApiResponse<int>.Warn("guid格式不正确");

            var user = await Task<User>.Run(() => _userService.GetUserByGuid(userGuid));

            return ApiResponse<int>.Success(user.IsRegistered() ? 1 : 0);
        }

    }
}
